<template>
  <el-alert
          title="提示"
          type="warning"
          description="批量导入请上传文件前仔细核验数据格式"
          show-icon
          :closable="false"
  />

  <div style="padding: 20px">
    <div style="display: flex;align-items:center;margin: 10px">
      <el-icon size="18">
        <FolderOpened/>
      </el-icon>
      <p style="margin-left:3px;font-size: 16px;font-weight: bolder;letter-spacing: 1px;color: #646464">文件上传</p>
    </div>
    <div style="display: flex;align-items:center;margin: 15px 0 15px 0">
      <div style="margin-right: 10px">
        <el-button type="success" :icon="SoldOut" style="height: 35px;line-height: 35px" @click="exportExcelTemplate">生成模板</el-button>
      </div>
      <div class="upload_box">
        <div>
          <span style="">{{ upload_file }}</span>
        </div>
        <input
                id="upload"
                type="file"
                accept=".xls,.xlsx"
                class="upload_file"
                @change="readFile($event)"
        />
      </div>
      <div style="margin-left: 10px">
        <el-button style="height: 35px;line-height: 35px" @click="resetFile">重置</el-button>
      </div>
    </div>
    <div style="display: flex;align-items:center;margin: 10px">
      <el-icon size="18">
        <View/>
      </el-icon>
      <p style="margin-left:3px;font-size: 16px;font-weight: bolder;letter-spacing: 1px;color: #646464">表格效果预览</p>
    </div>
    <el-table :data="tableData"
              border stripe
              style="width: 100%"
              :cell-style="{textAlign: 'center'}"
              :header-cell-style="{textAlign: 'center'}"
    >
      <el-table-column prop="zcmc" label="资产名称" width="120"/>
      <el-table-column prop="name" label="资产类别" width="120"/>
      <el-table-column prop="zcxh" label="资产型号" width="85"/>
      <el-table-column prop="zcdj" label="资产单价" width="120"/>
      <el-table-column prop="zcje" label="资产金额" width="100"/>
      <el-table-column prop="sccj" label="生产厂家" width="100"/>
      <el-table-column prop="scrq" label="生产日期" width="150"/>
      <el-table-column prop="gmrq" label="购买日期" width="165"/>
      <el-table-column prop="gmr" label="购买人" width="100"/>
      <el-table-column prop="zcsl" label="采购数量" width="85"/>
      <el-table-column prop="cght" label="采购合同" width="250" fixed="right">
        <template v-slot="scope">
          <el-upload
                  ref="uploadRef"
                  class="upload-demo"
                  :auto-upload="false"
                  accept=".pdf"
                  :show-file-list="false"
                  :on-change="handleChange"
          >
            <el-button :icon="Edit" type="primary" @click="handelReceive(scope.row.zcmc)">上传</el-button>
          </el-upload>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 15px">
      <el-button style="height: 35px;line-height: 35px" type="primary" @click="handleFileData">提交</el-button>
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, ref } from "vue";
import XLSX from "xlsx";
import { ElMessage, ElNotification } from 'element-plus'
import { Edit, FolderOpened, SoldOut, View } from '@element-plus/icons-vue';
import request, { exportExcel } from "@/util/request";
import moment from "moment";
import router from "@/router";

/**
 * vue3中操作ref实例的写法（proxy代替this）
 */
const {proxy} = getCurrentInstance()

/**
 * 初始化变量
 */
const upload_file = ref("请上传xls或者xlsx格式的文件");
const tableData = ref([]);


/**
 * 通用格式化时间信息
 * @param data
 * @returns {string}
 */
const currencyFormatDate = (data) => {
  let date = data;
  if (date === undefined) {
    return "";
  }
  return moment(date).format("YYYY-MM-DD");
}

/**
 * 导出模版excel
 */
const exportExcelTemplate = async () => {
  exportExcel("exportExcelTemplate").then((res) => {
    const objectUrl = URL.createObjectURL(
            new Blob([res.data], {
              type: 'application/vnd.ms-excel;charset=utf-8',
            })
    )
    const link = document.createElement('a')
    // 设置导出的文件名称
    link.download = "资产设备基本信息登记表" + ".xlsx"
    link.style.display = 'none'
    link.href = objectUrl
    link.click()
    document.body.appendChild(link)
  })
}

/**
 * 解析上传的文件
 */
const readFile = (e) => {
  let file = e.target.files[0];
  const types = ["xlsx", "xls"];
  const arr = file.name.split(".");
  //判断文件是否为excel文件
  if (!types.find(item => item === arr[arr.length - 1])) {
    alert('请选择正确的文件类型');
    return;
  }
  let reader = new FileReader();
  //启动函数
  reader.readAsBinaryString(file);
  reader.onload = e => {
    upload_file.value = file.name;
    //workbook存放excel的所有基本信息
    let workbook = XLSX.read(e.target.result, {type: "binary", cellDates: true});
    //定义sheetList中存放excel表格的sheet表，就是最下方的tab
    let sheetList = workbook.SheetNames;
    workbook.SheetNames.forEach(item => {
      console.log(XLSX.utils.sheet_to_json(workbook.Sheets[0]))
    })
    // range：设置从第几行开始读取内容
    let json = XLSX.utils.sheet_to_json(workbook.Sheets[sheetList[0]], {range: 2});
    let array = [];
    // 从解析出来的数据中提取相应的数据
    json.forEach(item => {
      array.push({
        zcmc: item["资产名称"],
        name: item["资产类别"],
        zcxh: item["资产型号"],
        zcdj: item["资产单价"],
        zcje: item["资产金额"],
        sccj: item["生产厂家"],
        scrq: currencyFormatDate(item["生产日期"]),
        gmrq: currencyFormatDate(item["购买日期"]),
        gmr: item["购买人"],
        zcsl: item["采购数量"],
      });
    });
    tableData.value = array;
  }
}

const zcmc = ref("")
const handelReceive = (name) => {
  zcmc.value = name;
}

let array = [];
let list = [];
const batchData = ref([]);
const handleChange = (file, fileList) => {
  if (!/\.(pdf)$/.test(file.name.slice(file.name.lastIndexOf('.')))) {
    ElNotification({
      title: '错误！！',
      message: '上传格式不正确，请上传PDF文件',
      type: 'error',
    })
    proxy.$refs.uploadRef.handleRemove(file);
  } else {
    ElNotification({
      title: '成功！！',
      message: '上传成功',
      type: 'success',
    })
    list.push({
      zcmc: zcmc.value,
      cght: file.name
    });
    batchData.value = list;
    array.push(fileList);
  }
}

/**
 * 重置上传文件
 */
const resetFile = () => {
  upload_file.value = "请上传xls或者xlsx格式的文件";
  tableData.value = [];
  document.getElementById("upload").value = "";
  array.length = 0;
}

/**
 * 提交解析的数据（批量添加）
 */
const handleFileData = async () => {
  if (!tableData.value.length > 0) {
    ElMessage({
      type: 'error',
      message: '请上传要解析的数据',
    })
  } else {
    if (array.length === 0) {
      console.log("fail")
      ElMessage({
        type: 'error',
        message: '请选择上传的合同',
      })
    } else {
      const res = await request.post("asset/batchSave", tableData.value);
      if (res.data.code === 200) {
        const res2 = await request.post("asset/batchSaveByName", batchData.value);
        if (res2.data.code === 200) {
          const fileList = new FormData();
          array.forEach((value) => {
            value.forEach((val) => {
              console.log(val.raw);
              fileList.append("files", val.raw)
            })
          })
          const res3 = await request.post("asset/uploadContractBatch", fileList);
          if (res3.data.code === 200) {
            ElMessage({
              type: 'success',
              message: '保存成功',
            })
            await router.replace("/assetsIndex")
          } else {
            ElMessage({
              type: 'error',
              message: '失败',
            })
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.upload_box {
  position: relative;

  div {
    width: 250px;
    height: 35px;
    line-height: 35px;
    text-align: center;
    background-color: #419fff;
    border-radius: 5px;
    z-index: 1;

    span {
      color: white;
      letter-spacing: 1px;
      font-size: 15px;
    }
  }

  .upload_file {
    position: absolute;
    top: 5px;
    left: 0;
    width: 160px;
    height: 44px;
    opacity: 0;
    cursor: pointer;
  }
}
</style>